<!-- 路由管理 -->
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import Container from '@/components/Container/index.vue'
import TableComponent from '@/components/TableComponent/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAsideStore } from '@store/aside'
import { columns, rules } from './options'
import {
  queryRoutes,
  addRoute,
  updateRoute,
  queryPrintRoutes,
  removeRoute,
} from '@/api/menu'
import type { FormInstance } from 'element-plus'
import type { MenuResponse, MenuRequest } from '@interface'

interface FormInterface {
  pid?: number
  name: string
  path: string
  component: string
  permission: string[]
  isSidebar: string
  meta: {
    title?: string
    icon?: string
    cache?: boolean
  }
}

defineOptions({
  name: 'MenuManager',
})

const asideStore = useAsideStore()

// 获取路由数据
const routeList = ref<MenuResponse[]>([])
const loading = ref(false)

const queryRouteList = async () => {
  try {
    loading.value = true
    // TODO: 这里的权限需要从用户的详情信息中获取
    const result = await queryRoutes({ permission: 1 })
    loading.value = false
    // console.table(result)
    routeList.value = result
    // 刷新侧边栏数据
    asideStore.updateAsideList(result)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取路由列表失败')
  }
}
onMounted(queryRouteList)

// 获取所有父级路由
const parentRouteList = ref<{ label: string; value: number }[]>([])

const queryParentRouteList = async () => {
  try {
    const result = await queryPrintRoutes()
    parentRouteList.value = result.map((item) => ({
      label: item.name,
      value: item.id,
    }))
  } catch (error) {
    ElMessage.error('获取父级路由列表失败')
  }
}
onMounted(queryParentRouteList)

const permissionOptions = ref<any[]>([
  {
    label: '超级管理员',
    key: 'superAdmin',
    value: '1',
  },
  {
    label: '管理员',
    key: 'admin',
    value: '2',
  },
  {
    label: '用户',
    key: 'user',
    value: '3',
  },
])

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const ruleFormRef = ref<FormInstance>()
const form = reactive<Partial<FormInterface>>({
  isSidebar: '0',
})

// 关闭dialog
const closeDialog = () => {
  dialogVisible.value = false
  reset()
  ruleFormRef.value?.clearValidate()
}

// 新增菜单
const handleAdd = () => {
  dialogType.value = 'add'
  reset()
  dialogVisible.value = true
}

const reset = () => {
  Object.assign(form, {
    isSidebar: '0',
    pid: undefined,
    name: '',
    path: '',
    component: '',
    permission: [],
  })
}

// 编辑菜单
const handleEdit = (row: MenuResponse) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    ...row,
    permission: row.permission ? row.permission.split(',') : [],
  })
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = async (id: number) => {
  if (!id) return
  try {
    const result = await ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
      type: 'warning',
    })
    if (result === 'confirm') {
      await removeRoute({ id: id })
      ElMessage.success('删除成功')
      queryRouteList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!ruleFormRef.value) return
  const formEl = ruleFormRef.value as FormInstance
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const dto = {
          ...form,
          meta: {},
          permission: form.permission?.join(','),
        }
        if (dialogType.value === 'add') {
          await addRoute(dto as MenuRequest)
        } else {
          await updateRoute(dto as MenuRequest)
        }
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
        dialogVisible.value = false
        queryRouteList()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
      }
    }
  })
}
</script>

<template>
  <Container
    class="menu-manager"
    title="路由管理"
    search
    :columns="['add']"
    @on:add="handleAdd"
  >
    <TableComponent
      :is-pagination="false"
      :columns="columns"
      :initial="routeList"
      v-loading="loading"
    >
      <template #path="{ scope: { row } }">
        <el-tag type="success">{{ row.path }}</el-tag>
      </template>
      <template #isSidebar="{ scope: { row } }">
        <el-tag>{{ row.isSidebar === 1 ? '是' : '否' }}</el-tag>
      </template>
      <template #pid="{ scope: { row } }">
        <span>{{ row.pid ? row.pid : '-' }}</span>
      </template>
      <template #action="{ scope: { row } }">
        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
        <el-button type="danger" link @click="handleDelete(row.id)">
          删除
        </el-button>
      </template>
    </TableComponent>
  </Container>

  <el-dialog
    :title="dialogType === 'add' ? '新增菜单' : '编辑菜单'"
    v-model="dialogVisible"
    @close="closeDialog"
  >
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="路由路径" prop="path">
        <el-input v-model="form.path" placeholder="请输入路由路径" />
      </el-form-item>
      <el-form-item label="文件路径" prop="component">
        <el-input v-model="form.component" placeholder="请输入文件路径" />
      </el-form-item>
      <el-form-item label="侧边栏">
        <el-switch
          v-model="form.isSidebar"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="权限配置" prop="permission">
        <el-select v-model="form.permission" multiple placeholder="请配置权限">
          <el-option
            v-for="item in permissionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="父级菜单">
        <el-select clearable v-model="form.pid" placeholder="请选择父级菜单">
          <el-option
            v-for="item in parentRouteList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use './index.scss';
</style>
